package gui;

import java.util.Arrays;
import image.Layer;

import com.sun.javafx.scene.control.skin.LabeledText;
import javafx.beans.binding.ListBinding;
import javafx.beans.property.ListProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.util.Callback;

public class ToolBarRight extends javafx.scene.control.ToolBar
{
	private final VBox box;

	private final ListView<String> listView;
	private final Text listText;
	private final Font listFont;

	public ToolBarRight(final Settings settings, final ImageManager imageManager)
	{
		super();
		this.setOrientation(Orientation.VERTICAL);
		this.setPrefWidth(150);
		this.setPrefHeight(ToolBar.HEIGHT);
		this.setStyle("-fx-background-color: " + Main.getBackground() + "; -fx-border-color: #888888");
		
		box = new VBox(2);
		
		listFont = Font.font("Arial", FontWeight.BOLD, 14);
		
		listText = new Text("Layers: ");
		listText.setFill(Color.WHITE);
		listText.setFont(listFont);

		listView = new ListView<String>();
		listView.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
            @Override public ListCell<String> call(ListView<String> list) 
            {
                return new CustomFormatCell();
            }
        });      
		ListBinding<String> binding = new ListBinding<String>()
		{
			{
				bind(imageManager.getActiveImage().layersProperty());
			}
			@Override protected ObservableList<String> computeValue()
			{
				String str = imageManager.getActiveImage().layersProperty().asString().get();
				if (str.length() > 2)
				{
					str = str.replace('[', ' ').replace(']', ' ').trim();
					String[] values = str.split(",");
					return FXCollections.observableList(Arrays.asList(values));
				}
				else
					return FXCollections.observableArrayList();
			}
			
		};
		listView.itemsProperty().bind(binding);
//		listView.itemsProperty().bind(imageManager.getActiveImage().layerNamesProperty());
		listView.setPrefHeight(this.getPrefHeight() - 10);
		listView.setPrefWidth(this.getPrefWidth() - 40);
		listView.setEditable(false);
		
		listView.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
			@Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) 
			{
				if (newValue.intValue() != -1)
					imageManager.getActiveImage().setActiveLayer(newValue.intValue());
			}
		});
		
		listView.setOnMouseDragged(new EventHandler<MouseEvent> () {
			@Override public void handle(MouseEvent arg0)
			{
				if (arg0.getTarget() instanceof LabeledText)
				{
					LabeledText target;
					target = (LabeledText)arg0.getTarget();
					
					ListProperty<Layer> layers = imageManager.getActiveImage().layersProperty();
					Layer targetL = imageManager.getActiveImage().getActiveLayer(); //settings.getTarget();
					if (targetL == null)
					{
						for (Layer l : layers)
						{
							if (l.toString().equals(target.getText().trim()))
							{
								targetL = l;
								settings.setTarget(targetL);
								break;
							}
						}
					}
					int i = imageManager.getActiveImage().layersProperty().indexOf(targetL);			
					
					if ( arg0.getY() - 26 * i > 40 )//* ( 1 + settings.getCount()) ) // - targetL.getY() > 3)
					{
						if ((i ) >= 0 && i  + 1 < layers.getSize())
						{
							layers.set(i, layers.get(i + 1));
							layers.set(i + 1, targetL);
							settings.setCounterPlusOne();
							listView.getSelectionModel().select(i + 1);
						}
					}
					else if ( arg0.getY() - 26 * (i - 1) < 20 )
					{
						if ((i - 1) >= 0 && i < layers.getSize())
						{
							layers.set(i, layers.get(i - 1));
							layers.set(i - 1, targetL);
							settings.setCounterMinusOne();
							listView.getSelectionModel().select(i - 1);
						}
					}
				}
			}
			
		});
		
		listView.setOnKeyPressed(new EventHandler<KeyEvent> () {
			@Override public void handle(KeyEvent event)
			{
				if (event.getCode() == KeyCode.DELETE)
				{
					if (listView.getSelectionModel().getSelectedItem() != null)
					{
						imageManager.getActiveImage().removeLayer(imageManager.getActiveImage().getActiveLayer());
						listView.getSelectionModel().clearSelection();
					}
				}
			}
		});
		
		listView.setOnMouseReleased(new EventHandler<MouseEvent> () {
			@Override public void handle(MouseEvent event)
			{
				settings.setTarget(null);
				settings.clearCounter();
			}
		});
		
		box.getChildren().addAll(listText, listView);
		this.getItems().add(box);
	}

	private static class CustomFormatCell extends ListCell<String>
	{
		@Override public void updateItem(String item, boolean empty)
		{
			super.updateItem(item, empty);

			
			if (item != null)
			{
				this.setWidth(150);
				this.setMinWidth(150);
				this.setContentDisplay(ContentDisplay.CENTER);
				this.setText(item + "                                   ");
			}
			else
				setText("");

		}

	}
}
